package com.anttribe.components.db.executor.formatter;

import java.util.HashMap;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

/**
 * @author zhaoyong
 * @date 2023/1/11 0011
 */
@Slf4j
public final class DataFormatterRegistry {

    private final Map<Integer, DataFormatter> DATA_FORMATTER_MAP = new HashMap<>();

    private DataFormatterRegistry() {
        this.register(new DateDateFormatter());
        this.register(new TimeDataFormatter());
        this.register(new TimestampDataFormatter());
    }

    /**
     * @return DataFormatterRegistry
     */
    public static DataFormatterRegistry me() {
        return DataFormatterRegistryInstance.INSTANCE;
    }

    /**
     * 注册类型对应的DataFormatter
     * 
     * @param dataFormatter
     *            DataFormatter
     */
    public void register(DataFormatter dataFormatter) {
        if (null == dataFormatter) {
            log.warn("Provided NON DataFormatter for register.");
            return;
        }

        MappedTypes mappedTypes = dataFormatter.getClass().getAnnotation(MappedTypes.class);
        if (null != mappedTypes) {
            DATA_FORMATTER_MAP.put(mappedTypes.type(), dataFormatter);
        }
    }

    /**
     * 注册类型对应的DataFormatter
     * 
     * @param type
     *            Types
     * @param dataFormatter
     *            DataFormatter
     */
    public void register(Integer type, DataFormatter dataFormatter) {
        if (null == type) {
            this.register(dataFormatter);
            return;
        }

        DATA_FORMATTER_MAP.put(type, dataFormatter);
    }

    /**
     * 根据类型获取DataFormatter
     * 
     * @param type
     *            Types
     * @return DataFormatter
     */
    public DataFormatter getDataFormatter(Integer type) {
        return DATA_FORMATTER_MAP.getOrDefault(type, null);
    }

    /**
     * 静态内部类实现单例
     */
    private static class DataFormatterRegistryInstance {

        private static final DataFormatterRegistry INSTANCE = new DataFormatterRegistry();
    }

}
